<template>
  <hr v-show="divided">
	<li 
    :class="disabled ? 'disabled' : ''" 
    @click.stop="liClick" 
    @mouseenter="openSubmenu($event)" 
    @mouseleave="closeSubmenu($event)"
  >
		<span class="title">
			<el-icon class="sc-contextmenu__icon"><component v-if="icon" :is="icon" /></el-icon>
			{{title}}
		</span>
		<span class="sc-contextmenu__suffix">
			<el-icon v-if="$slots.default"><el-icon-arrow-right /></el-icon>
			<template v-else>{{suffix}}</template>
		</span>
		<ul v-show="$slots.default" class="sc-contextmenu__menu">
			<slot />
		</ul>
	</li>
</template>

<script setup>
import {inject} from 'vue'

const menuClick = inject('menuClick')

let rects = {}

// eslint-disable-next-line
const props = defineProps({
  command: {type: String, default: ''},
  title: {type: String, default: ''},
  suffix: {type: String, default: ''},
  icon: {type: String, default: ''},
  divided: {type: Boolean, default: false},
  disabled: {type: Boolean, default: false},
})

function liClick(){
  const p = props
  if (p.disabled) return false
  menuClick(p.command)
  menuClick(p.command)
}
function openSubmenu(e) {
  const menu = e.target.querySelector('ul')
  if (!menu) return false
  menu.style.display = 'inline-block'
  const rect = menu.getBoundingClientRect()
  const menuX = rect.left
  const menuY = rect.top
  const innerWidth = window.innerWidth
  const innerHeight = window.innerHeight
  const menuHeight = menu.offsetHeight
  const menuWidth = menu.offsetWidth
  if (menuX + menuWidth > innerWidth) {
    menu.style.left = 'auto'
    menu.style.right = '100%'
  }
  if (menuY + menuHeight > innerHeight) {
    menu.style.top = 'auto'
    menu.style.bottom = '0'
  }
  rects = menu
}
function closeSubmenu(e) {
  const menu = e.target.querySelector('ul')
  if (!menu) return false
  menu.removeAttribute('style')
  menu.style.display = 'none'
}

// eslint-disable-next-line no-undef
defineExpose({rects})
</script>

<style scoped lang="scss">
@import './index.scss';
</style>
